Magento2 Events Observers

Hey Magento folks, this article is based on Magento2 1.0.0 beta version. I will be briefly explaining the event observers in Magento2. Developers who have worked on Magento 1.x series are well aware the importance of events-observers in terms of developing custom functionality, and a way to avoid core code modification.

In Magento2 , it is nearly the same concept, just the aesthetics of using it has changed. So lets dive into it without any further ado.

Contrary to Magento 1.x, all event defintions fo into a seperate xml file i.e events.xml

So in your module folder, there could be three events file.

  1. etc/events.xml
  2. etc/frontend/events.xml
  3. etc/adminhtml/events.xml

So as you might have guessed first file is for global scope and then frontend , adminhtml respectively.

So late’s say, i need to observer event, checkout_cart_add_product_complete

i will create an events.xml

<?xml version=“1.0” encoding=“UTF-8”?>
<config xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:noNamespaceSchemaLocation=“../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd”>
    <event name=“checkout_cart_add_product_complete”>
        <observer name=“techbuzz_custom_checkout_cart_add_product_complete” instance=“Techbuzz\Custom\Observer\CompleteObserver”  />
    </event>
</config>
ok, so here the in events tag, name is given as the event name. In the observer tag we have
1. name  = name of the observer – which should be unique
2. instance = class name which will contain this observer
So, in my module i.e. Techbuzz\Custom\Observer
<?php
namespace ‘Techbuzz\Custom\Observer’
use Magento\Framework\Event\ObserverInterface;
class CompleteObserver implements ObserverInterface
{
/**
* @param \Magento\Framework\Event\Observer $observer
* @return void
*
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
//execute your code here
}
}

Okie, so going deep into, how the events are initialize

//file \Magento\Checkout\Controller\Cart\Add.php -113

$this->_eventManager->dispatch(
‘checkout_cart_add_product_complete’,
[‘product’ => $product, ‘request’ => $this->getRequest(), ‘response’ => $this->getResponse()]
);

Where event manager is a object of \Magento\Framework\Event\ManagerInterface

So in same way we could initialize and fire our own custom events.

You can find list of events fired throughout Magento2 here

Leave a comment